<template>
  <div class="artList">
    <!-- 文章列表组件 -->
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      :success-duration="1000"
      :success-text="sucText"
    >
      <van-list
        :error.sync="isError"
        error-text="请求失败，点击重新加载"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ArtItem v-for="(art, i) in list" :key="i" :article="art"/>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getChannelArtList } from "@/api/article.js";
import ArtItem from "@/components/article-item/index.vue";
export default {
  name: "article-list",
  props: ["channel"],
  data() {
    return {
      refreshing: false,
      list: [],
      loading: false,
      finished: false,
      pre_time: Date.now(),
      sucText: "",
      isError: false,
    };
  },
  async created() {
    // const { data: resBody } = await getChannelArtList(
    //   this.channel.id,
    //   new Date()
    // );
    // this.list = resBody.data.results;
  },
  methods: {
    // 下拉请求最新的新闻数据
    async onRefresh() {
      try {
        if (Math.random() >= 0.5) {
          throw new Error("模拟随机报错");
        }
        const { data: resBody } = await getChannelArtList(
          this.channel.id,
          Date.now()
        );
        // console.log(resBody);
        // 将最新返回的数组和list数组中元素的id做对比
        let newList = resBody.data.results;
        let newList2 = [];
        newList.forEach((e) => {
          let isExsit = this.list.some((x) => x.art_id == e.art_id);
          if (!isExsit) {
            newList2.push(e);
          }
        });
        console.log("newList2", newList2);
        // 将返回的最新文章从数组头部加入
        this.list.unshift(...newList2);

        this.refreshing = false;
        this.sucText = "加载成功";
      } catch (error) {
        this.refreshing = false;
        this.sucText = "加载失败";
        console.log("报错啦：", error.message);
      }
    },
    // 触底更新
    async onLoad() {
      try {
        if (Math.random() >= 0.5) {
          throw new Error("模拟随机报错");
        }
        const { data: resBody } = await getChannelArtList(
          this.channel.id,
          this.pre_time
        );
        this.list.push(...resBody.data.results);
        // 将 返回的下一页时间戳给Date
        this.pre_time = resBody.data.pre_timestamp;
        // 手动将加载状态改成false
        this.loading = false;
      } catch (error) {
        console.log("触底加载出错啦：", error.message);
        this.isError = true;
        this.loading = false;
      }
    },
  },
  computed: {},
  watch: {},
  components: { ArtItem },
};
</script>

<style lang="less" scoped>
.artList {
  height: 79vh;
  overflow-y: auto;
}
</style>